package com.bilubi.reggie.reggie.service.Impl;

import com.bilubi.reggie.reggie.bean.Category;
import com.bilubi.reggie.reggie.enums.CodeEnum;
import com.bilubi.reggie.reggie.excpetion.CategoryDeleteException;
import com.bilubi.reggie.reggie.mapper.CategoryMapper;
import com.bilubi.reggie.reggie.mapper.DishMapper;
import com.bilubi.reggie.reggie.mapper.SetmealMapper;
import com.bilubi.reggie.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public Integer addCategory(Category category) {
        return categoryMapper.insert(category);
    }

    @Override
    public Integer updateCategoryById(Category category) {
        return categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    public Integer deleteCategoryById(Long id) {
        int count1 = dishMapper.selectCountByCategoryId(id);
        if (count1 > 0) {
            throw new CategoryDeleteException(CodeEnum.CATEGORY_ERROR_DISH);
        }
        int count2 = setmealMapper.selectCountByCategoryId(id);
        if (count2 > 0) {
            throw new CategoryDeleteException(CodeEnum.CATEGORY_ERROR_SETMEAL);
        }
        return categoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Category> findAllByType(Integer type) {
        return categoryMapper.selectAllByType(type);
    }
}
